<template>
    <div class="out-style">
        <Row :gutter="16">
            <Col span="10">
                <span class="tow-line-font">必须使用Excel模板进行数据导入，禁止对模板表结构进行修改</span>
            </Col>
            <Col span="12">
                <span class="tow-line-font2">
                    <a :href="templateHref" target="_Blank">下载此类数据的Excel模板</a>
                </span>
            </Col>
        </Row>
        <Row type="flex" justify="center">
            <Col span="22" offset="2">
                <div class="step-style">
                    <Steps :current="state">
                        <Step title="上传Excel"></Step>
                        <Step title="预览数据"></Step>
                        <Step title="导入数据"></Step>
                    </Steps>
                </div>
            </Col>
        </Row>
        <div v-show="state === 0">
            <Row>
                <Col>
                    <div class="four-line-font">您将通过上传的Excel文件，批量追加表格数据</div>
                    <div class="four-line-font">导入后只会保留Excel中的数据及通过公式计算后的值，设置的文字颜色等样式、合并的单元格、以及计算公式本身都不会被保留。</div>
                </Col>
            </Row>
            <Row>
                <Col>
                    <div class="last-line-upload">
                        <Upload
                                :before-upload="handleBeforeUpload"
                                action=""
                                accept=".xls, .xlsx"
                                type="drag">
                            <div class="upload-tip">
                                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                                <p>请导入.xls或.xlsx格式的Excel</p>
                            </div>
                        </Upload>
                    </div>
                </Col>
            </Row>
        </div>
        <div v-show="state === 1">
            <Row>
                <div v-if="file !== null" class="ivu-upload-list-file">
                    <Icon type="ios-stats"/>
                    {{ file.name }}
                    <Icon v-show="showRemoveFile" type="ios-close" class="ivu-upload-list-remove"
                          @click.native="handleRemove()"/>
                </div>
            </Row>
            <br>
            <Row>
                <Table border :columns="tableTitle" :data="tableData" :loading="tableLoading"/>
            </Row>
            <br>
            <Row type="flex" justify="end">
                <Col span="4">
                    <Button v-show="state === 1" @click="nextStep">下一步</Button>
                </Col>
            </Row>
        </div>
        <div v-show="state === 2">
            <br>
            <Row type="flex" :gutter="16" justify="center">
                <Col span="4">
                    <Button long @click="prevStep">上一步</Button>
                </Col>
                <Col span="4">
                    <Button long icon="ios-cloud-upload-outline" @click="excelBtn">导入到数据库</Button>
                </Col>
            </Row>
        </div>
        <Modal
                v-model="modalShow"
                title="提示"
                :loading="modalLoading"
                @on-ok="modalSubmit">
            <br>
            <h3 style="text-align: center">确认开始数据导入？</h3>
        </Modal>
    </div>
</template>

<script>
import excel from '@/libs/excel'
import { saveRecordpl } from '@/api/record'
import excelTemplate from './excel-template'

export default {
  props: {
    type: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  data () {
    return {
      state: 0,
      modalShow: false,
      modalLoading: true,
      uploadLoading: false,
      showRemoveFile: false,
      file: null,
      tableData: [],
      tableTitle: [],
      tableLoading: false,
      templateHref: ''
    }
  },
  methods: {
    // initTemplate () {
    //   switch (this.type) {
    //     case 'xxx':
    //       this.templateHref = excelTemplate.recordTemplate
    //       break
    //   }
    // },
    prevStep () {
      this.state = 1
    },
    nextStep () {
      this.state = 2
    },
    excelBtn () {
      this.modalShow = true
    },
    modalSubmit () {
      if (this.tableData.length === 0) {
        this.$Notice.warning({
          title: '请上传excel文件'
        })
      } else {
        const param = {
          dataList: this.tableData
        }
        this.modalLoading = true
        saveRecordpl(param).then(ret => {
          let data = ret.data
          if (data.errcode === 0) {
            this.modalLoading = false
            this.success()
            this.modalShow = false
          } else {
            this.modalLoading = false
            this.error(data)
          }
        })
      }
    },
    success () {
      this.$Message.success('操作成功')
    },
    error (data) {
      this.$Message.error({
        content: '操作失败,\n' + data.errmsg
      })
    },
    initUpload () {
      this.file = null
      this.state = 0
      this.tableData = []
      this.tableTitle = []
    },
    handleUploadFile () {
      this.initUpload()
    },
    handleRemove () {
      this.initUpload()
      this.$Message.info('上传的文件已删除！')
      this.state = 0
    },
    handleBeforeUpload (file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      if (fileExt === 'xlsx' || fileExt === 'xls') {
        this.readFile(file)
        this.file = file
      } else {
        this.$Notice.warning({
          title: '文件类型错误',
          desc: '文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。'
        })
      }
      return false
    },
    // 读取文件
    readFile (file) {
      const reader = new FileReader()
      reader.readAsArrayBuffer(file)
      reader.onloadstart = e => {
        this.uploadLoading = true
        this.tableLoading = true
        this.state = 0
      }
      reader.onprogress = e => {
        this.progressPercent = Math.round(e.loaded / e.total * 100)
      }
      reader.onerror = e => {
        this.$Message.error('文件读取出错')
      }
      reader.onload = e => {
        this.$Message.info('文件读取成功')
        const data = e.target.result
        const { header, results } = excel.read(data, 'array')
        const tableTitle = header.map(item => {
          return { title: results[0][item], key: item, minWidth: 200, align: 'center' }
        })
        this.tableData = results
        this.tableData.splice(0, 2) // 默认删除前两行数据
        this.tableTitle = tableTitle
        this.uploadLoading = false
        this.tableLoading = false
        this.showRemoveFile = true
        this.state = 1
      }
    }
  },
  mounted () {
    // this.initTemplate()
    // console.log('传入的类型', this.type)
    this.templateHref = excelTemplate.recordTemplate
  }
}
</script>

<style scoped>
    .out-style {
        padding: 10px;
    }

    .tow-line-font {
        font-size: 14px;
    }

    .tow-line-font2 {
        text-decoration: underline;
        font-size: 14px;
        color: #40A7FF;
        font-weight: 600;
        cursor: pointer;
    }

    .step-style {
        margin-top: 30px;
        margin-bottom: 30px;
    }

    .four-line-font {
        font-size: 14px;
    }

    .last-line-upload {
        margin-top: 20px;
    }

    .last-line-upload >>> .ivu-upload-drag {
        height: 230px;
        background: #fff;
        border: 1px dashed #dcdee2;
        border-radius: 4px;
        text-align: center;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: border-color .2s ease;
    }

    .upload-tip {
        padding-top: 75px;
    }
</style>
